import React, { useEffect, useState } from 'react'
import { SideBar } from 'antd-mobile'
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { connect } from 'react-redux';

function Category(props) {
  const { index, changeindex } = props;
  const [tabs, setTabs] = useState();
  const navigate = useNavigate();
  const [goodslist, setgoodslist] = useState();
  useEffect(()=>{
    axios('/categories?_embed=goods').then(res =>{
      setTabs(res.data);
      setgoodslist(res.data[index].goods);
    })
  },[index])
  return (
    <div style={{display:'flex'}}>
      <SideBar 
        style={{width:'4rem'}} 
        defaultActiveKey={String(index+1)}
        onChange={(value)=>{
          changeindex(value-1);
        }
      }>
        { tabs &&
          tabs.map(item => (
            <SideBar.Item key={item.id} title={item.title} />
          ))
        }
      </SideBar>
      <div style={
        {flex:1, 
         height:'calc(100% - 3.0625rem)',
         display:'flex', 
         justifyContent:'flex-start', 
         flexWrap:'wrap',
         alignItems:'flex-start',
         paddingBottom:'3.0625rem',
        }
      }>
        { goodslist &&
          goodslist.map(item => 
            <div key={item.id} style={{ height:'9rem', margin:'1rem .3rem', display:'flex', flexDirection:'column'}} onClick={()=>{
              navigate(`/auth/detail/${item.id}`)
            }}>
              <img style={{height:'100%'}} src={`http://localhost:5000/${item.poster}`} alt='加载失败'/>
              <span style={{textAlign:'center', width:'9rem'}}>{item.title}</span>
            </div>)
        }
      </div>
    </div>
  )
}

const mapStateToProps = (state) =>{
  return {
    index: state.categoryReducer.index
  }
}

const mapSwitchToProps = {
  changeindex(index){
    return {
      type: 'change-index',
      value: index
    }
  }
}

export default connect(mapStateToProps, mapSwitchToProps)(Category);
